var express = require('express')
var router = express.Router()
var jwt = require('jsonwebtoken')
// 导入db ,操作数据库
const { getAll, getById, exec } = require('../db/index')

const secret = 'register-rule'
/**
 * 获取所有用户
 * GET /blog
 */
router.get('/', async (req, res) => {
  console.log(req.query)
  // 解析请求参数
  // 解构query对象,提取page,size
  // 如果没有值,就给默认值1,2
  const { page = 1, size = 4 } = req.query
  // 获取总数
  let sql = `select count(*) as total  from bk_users`
  const obj = await getById(sql) // { total: 10 }
  console.log(obj)

  // 根据分页公式, 计算offset偏移量
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select * from bk_users order by user_id limit ${offset}, ${size}`
  const data = await getAll(sql)

  res.send({
    code: 0,
    message: '获取用户成功',
    result: {
      total: obj.total,
      data: data,
    },
  })
})

/**
 * 新增
 */

router.post('/', async (req, res) => {
  const { user_name, user_password } = req.body
  // const { page = 1, size = 2 } = req.query;
  let sql = `insert into bk_users (user_name,user_password)  values  ('${user_name}', '${user_password}')`
  const data = await exec(sql)
  console.log(data)
  res.send({
    code: 0,
    message: '新增用户成功',
    result: {
      user_id: data.insertId,
      user_name,
      user_password,
    },
  })
})

// 根据id获取
router.get('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `select user_id,user_name,user_password from bk_users where user_id = ${id}`
  const data = await getById(sql)
  res.send({
    code: 0,
    message: '获取用户成功',
    result: {
      data,
    },
  })
})

// 根据用户名查用户并分页--使用post可以不显示太长的参数,也可以用来保护密码
router.post('/username', async (req, res) => {
  const { page = 1, size = 4, user_name } = req.query
  //注意区分req.query和req.body,req.body是请求体
  /*  {
        "user_name": "admin",
      }*/
  // req.query是请求参数
  //?user_name=admin
  // 获取总数
  let sql = `select count(*) as total  from bk_users  where user_name like'%${user_name}%'`
  const obj = await getById(sql)
  console.log(obj)
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select * from bk_users where user_name like'%${user_name}%' order by user_id asc  limit ${offset}, ${size} `
  try {
    const data = await getAll(sql)
    res.send({
      code: 0,
      message: '获取用户成功',
      result: {
        total: obj.total,
        data: data,
      },
    })
  } catch (err) {
    res.send({
      code: 'err',
      message: '获取所有用户失败',
      result: debug ? '' : err,
    })
  }
})

// 修改请求
router.put('/:id', async (req, res) => {
  const { id } = req.params
  const { user_name, user_password } = req.body
  let sql = `update bk_users set user_name='${user_name}',
                                 user_password='${user_password}'
              where user_id=${id} `
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '修改用户成功',
    result: {
      user_id: id,
      user_name,
      user_password,
    },
  })
})

// 删除
router.delete('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `delete from bk_users where user_id=${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '删除成功',
    result: '',
  })
})

// 登录(demo版--只是测试,不要写到接口文档里)
router.post('/login', async (req, res) => {
  const { user_name, user_password } = req.body
  if (!user_name && !user_password) {
    return res.send({
      code: 100104,
      message: '参数格式不对',
      result: '用户密码不能为空',
    })
  }
  let sql = `select * from bk_users`
  const resData = await getAll(sql)
  console.log(resData)
  let user = resData.map((item) => item.user_name)
  // let ps = resData.map((item) => item.user_password);
  // let id = resData.map((item) => item.user_id);
  if (!user.includes(user_name)) {
    return res.send('该用户不存在')
  }
  if (user.includes(user_name)) {
    let sql1 = `select user_password from bk_users where user_name='${user_name}'`
    const psw = await getAll(sql1)
    console.log(psw)
    if (user_password == psw[0].user_password) {
      let token = jwt.sign({ user_name }, secret, { expiresIn: '24h' })
      return res.send({
        code: 0,
        message: '登录成功',
        result: {
          token,
        },
      })
    } else {
      return res.send({
        code: 1004,
        message: '密码错误',
      })
    }
  }
})

module.exports = router
